// pages/home/home.js
import {
  quearyAllNote,
  deleteNote,
  setItemTop,
  loadMore,
  getTotalCount,
  searchByKey
} from './../../api/nots.js'

import {
  getBackground,
  addBackground
} from './../../api/backgroud.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    msgTips: [
      "，你来啦？",
      "，你好嘛？",
      "，欢迎你！",
      "，回来啦！",
      "，来了呀！",
      "，到家了！",
    ],
    totalSize: 0, //总数
    bgUrl: "https://636c-cloud1-8g4peis6c08f195c-1306096204.tcb.qcloud.la/home_top_bg.png?sign=157f9ce48d62b5ac179919925f1289fa&t=1627702170",
    isDefaultBg: true //是否是默认背景
  },
  onLoad: function (options) {
    //首次进入加载数据
    this.onInit()
    //获取背景图片
    getBackground(0, 1).then(res => {
      console.log("getBackground", res)
      if (res.data.length) {
        this.setData({
          bgUrl: res.data[0].fileId,
          isDefaultBg: false
        })
      }

    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("onShow", this.data.editResult)
    //说明是从编辑页面点击保存或修改回来的
    if (this.data.editResult) {
      this.onPageBackResut()
    } else {
      console.log("不处理任何信息")
    }
    if (this.data.selectBg) {
      const fileId = this.data.selectBg.fileId
      delete this.data.selectBg
      this.setData({
        bgUrl: fileId
      })
    }
  },
  onInit() {
    wx.showLoading({
      title: '加载中...',
    })

    Promise.all([ getTotalCount(), quearyAllNote()]).then(res=>{
      console.log("all",res)
      wx.hideLoading()
      this.data.totalSize = res[0].total
      let list = res[1].list
      this.onRefreshList(list)
    })
    
    //初始化欢迎语
    let index = Math.floor((Math.random() * this.data.msgTips.length))
    let msg = this.data.msgTips[index]
    this.setData({
      isEmpty: true,
      msgTip: msg
    })
  },
  //检测是否显示加载更多
  checkShowLoading() {
    const query = wx.createSelectorQuery()
    query.select(".body").boundingClientRect().exec(res => {

      const {
        height
      } = res[0]
      const {
        windowHeight
      } = wx.getSystemInfoSync()
      const showLoading = height >= windowHeight
      this.setData({
        showLoading: showLoading,
      })
    })
  },
  //处理其它页面返回时携带的数据
  onPageBackResut() {
    let result = this.data.editResult
    let list = this.data.list
    if (this.data.searchKey) {
      //说明当前是搜索
      this.searchTitle({
        detail: {
          value: this.data.searchKey
        }
      })
      list = this.data.tempList
    }
    //说明是修改
    if (result.index >= 0) {
      list.splice(result.index, 1)
    } else {
      //添加
      this.data.total++
    }
    if (result.isTop) {
      //置顶数据
      list.unshift(result)
    } else {
      const len = list.length
      if (len > 0) {
        //当前有置顶的
        let tempItem = list[0]
        if (tempItem.isTop) {
          for (let i = 1; i < len; i++) {
            const item = list[i]
            //表示非置顶数据了
            if (!item.isTop) {
              list.splice(i, 0, result)
              break
            }
          }
        }
      } else {
        list.unshift(result)
      }
    }
    if (this.data.searchKey) {
      console.log("搜索 不刷新")
    } else {
      this.onRefreshList(this.data.list)
    }
  },
  //刷新页面
  onRefreshList(list) {
    let empty = (!list || list.length == 0)
    if (!empty) {
      list.map(item => {
        item.time = item.time.replace(" ", "\n")
      })
    }
    this.setData({
      isEmpty: empty,
      list: list,
      isLoadMore: this.isLoadMore()
    },()=>{
      this.checkShowLoading()
    })
    //清空返回的数据
    delete this.data.editResult
  },
  /**
   * 点击新建按钮
   */
  onClickNewBtn: function () {

    wx.navigateTo({
      url: './../edit/edit?action=0',
    })
  },

  /**
   * 更换文字提示
   */
  onClickMsg: function () {
    //从数组中随机获取
    let index = Math.floor((Math.random() * this.data.msgTips.length))
    let msg = this.data.msgTips[index]
    console.log('onClickMsg', index)
    this.setData({
      msgTip: msg
    })
  },
  /**
   * 修改
   */
  onClickEdit(e) {
    let data = e.currentTarget.dataset
    let item = data.item
    let index = data.index
    wx.navigateTo({
      url: './../edit/edit?action=1&index=' + index + '&item=' + JSON.stringify(item),
    })
  },
  /**
   * 删除item
   */
  deleteItem(index) {
    //删除数据
    let list = this.data.list
    //搜索
    if (this.data.searchKey) {
      const {
        _id
      } = list[index]
      this.data.tempList = this.data.tempList.filter(item => item._id !== _id)
    }

    list.splice(index, 1)
    let empty = (!list || list.length == 0)
    console.log("empty:" + empty + " list:" + list)
    this.setData({
      isEmpty: empty,
      list: list
    },()=>{
      this.checkShowLoading()
    })

  },
  deleteNetworkNote(index, data) {
    console.log("deleteNetworkNote", data)
    wx.showLoading({
      title: '删除中...',
    })
    data.index = index
    deleteNote(data).then(res => {
      wx.hideLoading()
      this.deleteItem(index)
      wx.showToast({
        title: '删除成功'
      })
    })
  },
  //置顶
  onTopChange: function (e) {
    console.log("onTopChange", e)
    const data = e.currentTarget.dataset
    const index = data.index
    const item = data.item
    item.slideShow = false
    if (item.isTop) {
      //取消置顶
      item.isTop = false
      //临时时间减去 置顶是的时间
      item.newTime = item.newTime - item.setTopTime
      //置顶时间设置为0
      item.setTopTime = 0
      setItemTop(item).then(res => {
        console.log("success", res)
      }).catch(res => {
        console.log("error", res)
      })
      //删除
      this.data.list.splice(index, 1)
      //添加
      this.data.list.unshift(item)
      //排序
      this.data.list.sort((a, b) => b.newTime - a.newTime)
      if (this.data.searchKey) {
        //搜索
        const _id = item._id
        this.data.tempList = this.data.tempList.filter(item => item._id !== _id)
        //添加
        this.data.tempList.unshift(item)
        //排序
        this.data.tempList.sort((a, b) => b.newTime - a.newTime)
      }
    } else {
      //设置置顶
      item.isTop = true
      //置顶时间
      item.setTopTime = Date.now()
      //设置临时时间
      item.newTime += item.setTopTime
      //操作数据库
      setItemTop(item).then(res => {
        console.log("success", res)
      }).catch(res => {
        console.log("error", res)
      })
      console.log("置顶", item)
      //删除
      this.data.list.splice(index, 1)
      //添加到最上面
      this.data.list.unshift(item)

      if (this.data.searchKey) {
        //搜索
        const _id = item._id
        this.data.tempList = this.data.tempList.filter(item => item._id !== _id)
        //添加
        this.data.tempList.unshift(item)
      }

    }
    this.setData({
      list: this.data.list
    })
  },
  //删除
  onItemDel: function (e) {
    console.log("onItemDel", e)
    let that = this;
    wx.showModal({
      title: '提示',
      content: "是否删除该条数据?",
      success(res) {
        if (res.confirm) {
          let data = e.currentTarget.dataset
          let index = data.index

          that.deleteNetworkNote(index, data.item)
        }
      }
    })
  },
  onPullDownRefresh() {
    //查询全部记录
    quearyAllNote().then(res => {
      console.log(res)
      wx.stopPullDownRefresh()


      this.onRefreshList(res.list)
    }).catch(res => {
      console.log("error", res)
      wx.stopPullDownRefresh()
    })
  },
  onReachBottom() {

    const skip = this.data.list.length
    if (this.isLoadMore()) {
      loadMore(skip, 20).then(res => {
        let index = skip
        let changeData = {}
        res.list.forEach(item => {
          changeData['list[' + (index++) + ']'] = item
        })
        console.log("changeData", changeData)
        changeData['isLoadMore'] = this.isLoadMore()
        this.setData(changeData)
      })
    } else {
      console.log("到底了")
      this.setData({
        isLoadMore: false
      })
    }

  },
  //是否加载更多
  isLoadMore() {
    const key = this.data.searchKey
    if (key) return false
    const skip = this.data.list.length
    return this.data.totalSize > skip
  },
  //item滑动显示
  onSlideShow(e) {
    console.log("onSlideShow", e)
    const index = e.currentTarget.dataset.index
    const currentSlideShow = 'list[' + index + '].slideShow'
    const preSlideShow = this.data.currentSlideShow
    if (preSlideShow) {
      this.setData({
        [preSlideShow]: false
      })
    }
    this.setData({
      currentSlideShow: currentSlideShow,
      [currentSlideShow]: true
    })
  },

  onRootTouchStart(e) {
    const preSlideShow = this.data.currentSlideShow
    if (preSlideShow) {
      this.setData({
        [preSlideShow]: false,
        currentSlideShow: null
      })

    }
  },
  //添加图片
  onImageAdd(e) {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: '图片上传中...',
        })
        const filePath = res.tempFilePaths[0]
        const cloudPath = `note-bg-url/${Date.now()}-${Math.random(0, 1) * 100000}` + filePath.match(/.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success(res) {
            console.log('上传成功后获得的res：', res)
            const fileID = res.fileID
            addBackground(res.fileID).then(res => {
              console.log("add", res)
              wx.hideLoading()
              that.setData({
                bgUrl: fileID
              })
            })

          },
          fail(res) {
            console.log('上传失败后获得的res：', res)
          }
        })
      }
    })
  },
  onImageClick() {
    wx.navigateTo({
      url: './../backgroud/background',
    })
  },
  searchTitle(e) {
    const key = e.detail.value
    console.log("searchTitle", key)
    if (!this.data.searchKey) {
      //将正常数据保存
      this.data.tempList = this.data.list
    }
    searchByKey(key).then(res => {
      const list = res.list
      let empty = (!list || list.length == 0)
      if (!empty) {
        list.map(item => {
          item.time = item.time.replace(" ", "\n")
        })
      }
      this.setData({
        searchKey: this.trim(key),
        list: list,
        isLoadMore: false
      })
    })
  },
  // 去除首尾的空格
  trim: function (s) {
    return s.replace(/(^\s*)|(\s*$)/g, "");
  },
  onSearchClear(e) {
    console.log("onSearchClear", e)
    const list = this.data.tempList
    delete this.data.tempList
    this.setData({
      searchKey: null,
      list: list,
      isLoadMore: this.isLoadMore()
    })
  },
  // initSearchBar(){
  //   let t = this, sbar = this.selectComponent("#searchbar"),
  //   { hideInput ,clearInput} = sbar
  //   console.log(this.selectComponent("#searchbar"))

  //   // 重写
  //   Object.defineProperties(sbar.__proto__, {
  //     hideInput:{
  //       configurable: true,
  //       enumerable: true,
  //       writable: true,
  //       value(...p){
  //          // 加上这句，同时wxml需要加上bindcancel="cancel"
  //         // this.triggerEvent('cancel', {})
  //         // 或者这里直接调用下面的cancel方法，那么wxml就不需要bindcancel
  //         // t.onSearchCancel()

  //         // 执行原方法，返回原方法结果
  //         return hideInput.apply(sbar, p)
  //       }
  //     }
  //   })
  // },

  onSearchCancel(e) {
    console.log("onSearchCancel", e)
    if (this.data.searchKey) {
      this.onSearchClear(e)
    }

  }
})